/*******************************************************************************
**
** Copyright (c) 2011 - The OWE Team
**
** This file is part of OWE.
**
** OWE is a free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; version
** version 2.1 of the License.
**
** OWE is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with OWE. If not, see <http://www.gnu.org/licenses/>.
**
*******************************************************************************/

#include <QString>
#include <QByteArray>

#include <owe/ustring.h>

#include "ustring_p.h"

OWE_USE_NAMESPACE

UStringPrivate::UStringPrivate(const char *str)
{
    if (str)
        string = qstrdup(str);
    else
        string = qstrdup("");
}

UString::UString(const char *str)
    : d_ptr(new UStringPrivate(str))
{
}

UString::~UString()
{
    delete [] d_ptr->string;
    delete d_ptr;
}

UString::UString(const UString &other)
    : d_ptr(new UStringPrivate(0))
{
    delete [] d_ptr->string;
    d_ptr->string = qstrdup(other.d_ptr->string);
}

UString &UString::operator=(const UString &other)
{
    if (this == &other)
        return *this;

    delete [] d_ptr->string;
    d_ptr->string = qstrdup(other.d_ptr->string);

    return *this;
}

int UString::compare(const char *uchar) const
{
    // TODO: Not optimal, same reasons as stated in append().
    return QString::fromUtf8(d_ptr->string).compare(QString::fromUtf8(uchar));
}

UString &UString::append(const UString &ustr)
{
    // TODO: Verify if UTF-8 concatenation can be made as usual. Not sure if the
    // buffers can by just appended.
    //
    // This is really expensive, avoid concatenation on OWE side while using the
    // Qt port. Unfortunately QString is UTF-16, lots of conversions are needed.
    QString concat = QString::fromUtf8(d_ptr->string) + QString::fromUtf8(ustr.d_ptr->string);
    QByteArray array = concat.toUtf8();

    delete [] d_ptr->string;
    d_ptr->string = qstrdup(array.constData());

    return *this;
}

int UString::size() const
{
    return QString::fromUtf8(d_ptr->string).size();
}

const char *UString::data() const
{
    return d_ptr->string;
}

UString &UString::simplified()
{
    QString simp = QString::fromUtf8(d_ptr->string).simplified();
    QByteArray array = simp.toUtf8();

    delete [] d_ptr->string;
    d_ptr->string = qstrdup(array.constData());

    return *this;
}
